package com.zq.behavior.observer;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

public interface Subject {
    // 由于将观察者注册到主题上。主题只负责调用观察者的update方法，其他不管，所以可以不用将观察者抽成范型
    Subject register(Observer observer);
    Subject unregister(Observer observer);
    // 这个Object根据自己业务情况
    void notifyAllObservers(Object object);
}

class ConcreteSubject implements Subject {

    private List<Observer> subjects;

    ConcreteSubject() {
        subjects = new LinkedList<>();
    }

    @Override
    public ConcreteSubject register(Observer observer) {
        subjects.add(Objects.requireNonNull(observer));
        return this;
    }

    @Override
    public ConcreteSubject unregister(Observer observer) {
        if (observer == null) {
            return this;
        }

        subjects.remove(observer);
        return this;
    }

    @Override
    public void notifyAllObservers(Object object) {
        subjects.forEach(observer -> observer.update(object));
    }
}
